<template>
  <div class="parts-management">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="配件名称">
          <el-input
              v-model="searchForm.name"
              placeholder="输入配件名称"
              clearable
              @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="存放位置">
          <el-input
              v-model="searchForm.location"
              placeholder="输入存放位置"
              clearable
              @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="所属设备">
          <el-input
              v-model="searchForm.equipment"
              placeholder="输入设备名称"
              clearable
              @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon>新增配件
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column prop="name" label="配件名称" width="180" />
        <el-table-column prop="quantity" label="库存数量" width="120" sortable>
          <template #default="{ row }">
            <span :class="{ 'low-stock': row.quantity < 10 }">
              {{ row.quantity }}
              <el-icon v-if="row.quantity < 10" color="red">
                <Warning />
              </el-icon>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="存放位置" width="200" />
        <el-table-column prop="equipment" label="所属设备" width="200" />
        <el-table-column prop="lastUpdate" label="最后更新时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(row)"
            >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form
          :model="formData"
          :rules="formRules"
          ref="formRef"
          label-width="120px"
      >
        <el-form-item label="配件名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入配件名称" />
        </el-form-item>
        <el-form-item label="库存数量" prop="quantity">
          <el-input-number
              v-model="formData.quantity"
              :min="0"
              :step="1"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="存放位置" prop="location">
          <el-input v-model="formData.location" placeholder="请输入存放位置" />
        </el-form-item>
        <el-form-item label="所属设备" prop="equipment">
          <el-input v-model="formData.equipment" placeholder="请输入所属设备" />
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="formData.specification" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Plus, Warning } from '@element-plus/icons-vue'

interface PartItem {
  id: number
  name: string
  quantity: number
  location: string
  equipment: string
  specification?: string
  remark?: string
  lastUpdate: string
}

// 搜索表单
const searchForm = ref({
  name: '',
  location: '',
  equipment: ''
})

// 表格数据
const tableData = ref<PartItem[]>([])

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const formData = ref<PartItem>({
  id: 0,
  name: '',
  quantity: 0,
  location: '',
  equipment: '',
  specification: '',
  remark: '',
  lastUpdate: ''
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入配件名称', trigger: 'blur' }],
  quantity: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存不能小于0', trigger: 'blur' }
  ],
  location: [{ required: true, message: '请输入存放位置', trigger: 'blur' }],
  equipment: [{ required: true, message: '请输入所属设备', trigger: 'blur' }]
}

// 加载状态
const loading = ref(false)
const formRef = ref<FormInstance>()

// 获取配件列表
const fetchPartsList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    // 模拟数据
    const mockData: PartItem[] = Array.from({ length: 45 }, (_, i) => ({
      id: i + 1,
      name: `配件-${i + 1}`,
      quantity: Math.floor(Math.random() * 100),
      location: ['仓库A', '仓库B', '仓库C'][i % 3] + `-${(i % 20) + 1}区`,
      equipment: `设备-${i % 10 + 1}`,
      specification: `SPEC-${i % 5}`,
      lastUpdate: new Date().toISOString().slice(0, 10),
      remark: i % 4 === 0 ? '易损件' : ''
    }))

    // 过滤数据
    let filteredData = mockData.filter(item => {
      return (
          item.name.includes(searchForm.value.name) &&
          item.location.includes(searchForm.value.location) &&
          item.equipment.includes(searchForm.value.equipment)
      )
    })

    // 分页处理
    pagination.value.total = filteredData.length
    const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
    const end = start + pagination.value.pageSize
    tableData.value = filteredData.slice(start, end)
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchPartsList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = { name: '', location: '', equipment: '' }
  handleSearch()
}

// 显示新增对话框
const showAddDialog = () => {
  formData.value = {
    id: 0,
    name: '',
    quantity: 0,
    location: '',
    equipment: '',
    specification: '',
    remark: '',
    lastUpdate: ''
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 模拟新增数据
  const newPart = {
    ...formData.value,
    id: tableData.value.length + 1,
    lastUpdate: new Date().toISOString().slice(0, 10)
  }

  tableData.value = [newPart, ...tableData.value]
  ElMessage.success('操作成功')
  dialogVisible.value = false
  fetchPartsList()
}

// 删除配件
const handleDelete = (row: PartItem) => {
  ElMessageBox.confirm('确定删除该配件吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableData.value = tableData.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  fetchPartsList()
}

const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val
  fetchPartsList()
}

onMounted(() => {
  fetchPartsList()
})
</script>

<style scoped>
.parts-management {
  padding: 20px;
}

.search-container {
  background-color: #f5f7fa;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.action-buttons {
  margin-bottom: 20px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.low-stock {
  color: #f56c6c;
  font-weight: bold;
}
</style>